package cn.com.surker.system.service.impl;

import cn.com.surker.base.system.dao.SysControlStorageDao;
import cn.com.surker.base.system.dao.SysLineDao;
import cn.com.surker.base.system.dao.SysStorageLogDao;
import cn.com.surker.base.system.dao.SysStorageMatchDao;
import cn.com.surker.base.system.entity.SysControlStorage;
import cn.com.surker.base.system.entity.SysLine;
import cn.com.surker.base.system.entity.SysStorageLog;
import cn.com.surker.base.system.entity.SysStorageMatch;
import cn.com.surker.common.MessageCenterException;
import cn.com.surker.database.JDBCTemplateCache;
import cn.com.surker.dto.system.SysStorageMatchDTO;
import cn.com.surker.spring.RestResultDto;
import cn.com.surker.system.service.SysControlStorageService;
import cn.com.surker.util.DateUtil;
import cn.com.surker.util.StringUtils;
import cn.com.surker.vo.system.SysStorageMatchVO;
import cn.com.surker.workcon.service.StorXMaterService;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author lucky
 * @create 2024年10月31 9:21
 * @desc
 */
@Service
public class SysControlStorageServiceImpl implements SysControlStorageService {

    @Resource
    private SysControlStorageDao controlStorageDao;
    @Resource
    private SysLineDao lineDao;
    @Resource
    private SysStorageMatchDao storageMatchDao;
    @Resource
    private SysStorageLogDao sysStorageLogDao;

	@Autowired
	private StorXMaterService storXMaterService;

    /**
     * 查询所有工控仓位信息
     * @return
     */
    public List<SysControlStorage> findAll() {
        QueryWrapper<SysControlStorage> query = new QueryWrapper<>();
        query.eq("status", 0);
        query.orderByAsc("line_id");
        List<SysControlStorage> list = controlStorageDao.selectList(query);
        if (list == null || list.size() == 0)
            return null;
        return list;
    }

    /**
     *
     * @param searchVal
     * @param offset
     * @param limit
     * @return
     */
    public IPage findPage(String searchVal, Long lineId, Integer offset, Integer limit) {
        PageHelper.offsetPage(offset, limit);
        QueryWrapper<SysControlStorage> query = new QueryWrapper<>();
        query.eq("status", 0);
        if (ObjectUtil.isNotEmpty(lineId))
            query.eq("line_id", lineId);
        if (!StringUtils.isNull(searchVal)) {
            query.and(orderWrapper -> orderWrapper.like("name", searchVal).or()
                    .like("material_name", searchVal).or().like("remark", searchVal));
        }

        query.orderByDesc("create_time");

        IPage<SysControlStorage> iPage = controlStorageDao.selectPage(new Page<>((offset + limit) /limit, limit), query);
        /**分页插件**/
        if (!StringUtils.isNull(iPage.getRecords())) {
            PageInfo pageInfo = new PageInfo(iPage.getRecords());
            if (!StringUtils.isNull(pageInfo.getTotal()))
                iPage.setTotal(pageInfo.getTotal());
        }
        return iPage;
    }

    /**
     * 保存工控仓位
     * @param controlStorage
     * @return
     */
    public RestResultDto saveControl(SysControlStorage controlStorage) {
        if (controlStorage == null)
            throw new MessageCenterException("参数错误");
        QueryWrapper<SysControlStorage> query = new QueryWrapper<>();
        query.eq("status", 0);
        query.eq("line_id", controlStorage.getLineId());
        query.eq("org_id", controlStorage.getOrgId());
        query.eq("name", controlStorage.getName());
        Integer total = controlStorageDao.selectCount(query);
        if (total > 0)
            throw new MessageCenterException("同一生产线存在同样名称");
        SysLine line = lineDao.selectById(controlStorage.getLineId());
        if (line == null || line.getStatus() == 1)
            throw new MessageCenterException("生产线不存在或已被删除");
        controlStorage.setCreateTime(new Date());
        Integer code = controlStorageDao.insert(controlStorage);
        if (code > 0) {//保存工控代码
			Long controlId = storXMaterService.insertStore(line, controlStorage);
            if (controlId < 1)
                throw new MessageCenterException("保存工控系统仓位异常");
//            StorXMater storXMater = new StorXMater(line.getControlLineId().intValue(), controlStorage.getName(), controlStorage.getMaterialName(), controlStorage.getCreateTime());
//            code = storXMaterDao.insert(storXMater);
//            if (code > 0) {
            controlStorage.setControlId(controlId);//工控仓位ID
            code = controlStorageDao.updateById(controlStorage);
            if (code > 0)
                return RestResultDto.success("保存成功", controlStorage);
//            }
        }
        throw new MessageCenterException("保存工程仓位信息失败");
    }

    /**
     * 更新工控仓位
     * @param controlStorage
     * @return
     */
    public RestResultDto updateControl(SysControlStorage controlStorage)  {
        if (controlStorage == null || StringUtils.isNull(controlStorage.getId()))
            throw new MessageCenterException("参数错误");
        SysControlStorage storage = controlStorageDao.selectById(controlStorage.getId());
        if (storage == null || storage.getStatus() == 1)
            throw new MessageCenterException("业务数据不存在或已禁用");
        if (StringUtils.isNull(storage.getControlId()) || storage.getControlId() < 1)
            throw new MessageCenterException("工控系统仓位ID为空");
        Date nowDate = new Date();
        if (!StringUtils.isNull(controlStorage.getName()) && !controlStorage.getName().equals(storage.getName())) {
            QueryWrapper<SysControlStorage> query = new QueryWrapper<>();
            query.eq("status", 0);
            query.eq("line_id", controlStorage.getLineId());
            query.eq("org_id", controlStorage.getOrgId());
            query.eq("name", controlStorage.getName());
            Integer total = controlStorageDao.selectCount(query);
            if (total > 0)
                throw new MessageCenterException("同一生产线存在同样名称");
            //工控仓位变更记录
            SysStorageMatchDTO matchDTO = new SysStorageMatchDTO();
            matchDTO.setControlId(controlStorage.getId());
            matchDTO.setStatus(0);
            List<SysStorageMatchVO> matchVOList = storageMatchDao.page(matchDTO);
            if (matchVOList != null && matchVOList.size() > 0) {
                List<SysStorageLog> logList = new ArrayList<>();
                for (int i = 0; i < matchVOList.size(); i++) {
                    SysStorageMatchVO matchVO = matchVOList.get(i);
                    SysStorageLog storageLog = new SysStorageLog(storage.getOrgId(), storage.getId(), storage.getName(),
                            controlStorage.getName(), matchVO.getMaterialId(), matchVO.getMaterialName(),
                            matchVO.getLineId(), 1, nowDate, controlStorage.getUpdator(), nowDate);
                    storageLog.setStatus(0);
                    logList.add(storageLog);
                }
                if (logList != null && logList.size() > 0) {
                    Integer code = sysStorageLogDao.saveBatch(logList);
                    if (code < 1)
                        throw new MessageCenterException("更新工控仓位变更记录错误~！");
                }
            }
        }
        SysControlStorage oldStorage = storage;
        SysLine line = lineDao.selectById(controlStorage.getLineId());
        if (line == null || line.getStatus() == 1)
            throw new MessageCenterException("生产线不存在或已被删除");
        if (!StringUtils.isNull(controlStorage.getType()))
            storage.setType(controlStorage.getType());
        if (!StringUtils.isNull(storage.getName()) && !StringUtils.isNull(controlStorage.getName())
                && !storage.getName().equals(controlStorage.getName())) {
            storage.setName(controlStorage.getName());
            QueryWrapper<SysStorageMatch> query = new QueryWrapper<>();
            query.eq("status", 0);
            query.eq("control_id", storage.getId());
            Integer total = storageMatchDao.selectCount(query);
            if (total > 0) {
                UpdateWrapper<SysStorageMatch> uw = new UpdateWrapper<>();
                uw.set("control_storage", controlStorage.getName());
                uw.set("update_time", nowDate);
                if (!StringUtils.isNull(controlStorage.getCreator()))
                    uw.set("updator", controlStorage.getCreator());
                uw.eq("control_id", storage.getId());
                Integer resultCode = storageMatchDao.update(new SysStorageMatch(), uw);
                if (resultCode < 1)
                    throw new MessageCenterException("更新工控系统仓位名称异常");
            }
        }
        storage.setMaterialName(controlStorage.getMaterialName());
        storage.setUpdateTime(nowDate);
        if (!StringUtils.isNull(controlStorage.getUpdator()))
            storage.setUpdator(controlStorage.getUpdator());

        Integer code = controlStorageDao.updateById(storage);
        if (code > 0) {//
            controlStorage.setControlCreateTime(DateUtil.convertString(nowDate));
			Long controlId = storXMaterService.updateStore(line, oldStorage, controlStorage);
            if (controlId.intValue() == 0) {
                return RestResultDto.success("更新成功", storage);
            } else if (controlId.intValue() > 0) {
                controlStorage.setControlId(controlId);//工控仓位ID
                return RestResultDto.success("更新成功", storage);
            } else {

                throw new MessageCenterException("更新工控系统仓位信息异常");
            }
        }
        throw new MessageCenterException("更新工控仓位信息失败");
    }

    /**
     * 更新工控仓位状态
     * @param id
     * @param status
     * @param creator
     * @param remark
     * @return
     */
    public RestResultDto updateStatus(Long id, Integer status, String creator, String remark) {
        if (StringUtils.isAllParamNull(id, status))
            throw new MessageCenterException("参数错误");

        SysControlStorage storage = controlStorageDao.selectById(id);
        if (storage == null)
            throw new MessageCenterException("参数错误");
//        storage.setStatus(status);
//        if(!StringUtils.isNull(creator))
//            storage.setUpdator(creator);
//        if(!StringUtils.isNull(remark))
//            storage.setRemark(remark);
//        storage.setUpdateTime(new Date());
        Integer code = controlStorageDao.updateById(storage);
        if (code > 0) {
            //TODO 缺少同步写入工控仓位信息代码
            return RestResultDto.success("更新成功", storage);
        }
        throw new MessageCenterException("更新工程仓位信息失败");
    }

    /**
     * 新增工控仓位
     * @param line
     * @param controlStorage
     * @return
     */
    /*private Long insertStore(SysLine line, SysControlStorage controlStorage) {
        if (line.getProducer().equals("中青林")) {
            String sql = "insert into StorXMater (Storage,Material,DatTim,Station) values (?,?,?,?)";
            Object[] obj = {controlStorage.getName(), controlStorage.getMaterialName(), controlStorage.getControlCreateTime(), line.getControlLineId()};
            JdbcTemplate jdbcTemplate = JDBCTemplateCache.getLineJdbcTemplate(line);
            KeyHolder keyHolder = new GeneratedKeyHolder();
            jdbcTemplate.update(new PreparedStatementCreator() {
                public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                    PreparedStatement ps = connection.prepareStatement(sql, new String[]{"ID"});
                    for (int i = 0; i < obj.length; i++) {
                        ps.setObject(i + 1, obj[i]);
                    }
                    return ps;
                }
            }, keyHolder);
            Long taskId = keyHolder.getKey().longValue();
            if (taskId > 1)
                return taskId;
            return -1l;
        }

        return -1l;
    }*/
    /**
     * 修改工控仓位
     * @param line
     * @param controlStorage
     * @return
     */
    /*private Long updateStore(SysLine line, SysControlStorage oldControlStorage, SysControlStorage controlStorage) {
        if (line.getProducer().equals("中青林")) {
            JdbcTemplate jdbcTemplate = JDBCTemplateCache.getLineJdbcTemplate(line);
            String querySql = "select * from StorXMater where station = " + line.getControlLineId()
                    + " and Storage = '" + oldControlStorage.getName() + "'";
            List<Map<String, Object>> mapList = jdbcTemplate.queryForList(querySql);
            if (mapList == null || mapList.size() == 0) {
                return insertStore(line, controlStorage);
            } else {
                String updateSql = "update StorXMater set Station=" + line.getControlLineId() + ",DatTim = '" + controlStorage.getControlCreateTime() + "' ";
                if (!StringUtils.isNull(controlStorage.getName()))
                    updateSql += " ,Storage ='" + controlStorage.getName() + "' ";
                if (!StringUtils.isNull(controlStorage.getMaterialName()))
                    updateSql += " ,Material ='" + controlStorage.getMaterialName() + "' ";
                updateSql += " where id = " + mapList.get(0).get("ID");
                Integer code = jdbcTemplate.update(updateSql);
                if (code > 0)
                    return 0l;
                return -1l;
            }
        }
        return -1l;
    }*/
}
